use crate::controls::buttons;
use windows_sys::{
    Win32::Foundation::*, Win32::Graphics::Gdi::*, Win32::System::LibraryLoader::GetModuleHandleW,
    Win32::UI::Controls::*, Win32::UI::WindowsAndMessaging::*, core::*,
};

pub struct MsgInfo {
    pub id: u32,
    pub event: u32,
    pub window: HWND,
    pub message: u32,
    pub wparam: WPARAM,
    pub lparam: LPARAM,
}

impl MsgInfo {
    pub fn new(window: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> Self {
        Self {
            id: (wparam & 0xffffffff) as u32,
            event: ((wparam >> 32) & 0xffffffff) as u32,
            window,
            message,
            wparam,
            lparam,
        }
    }
}

pub fn wm_create(info: MsgInfo) -> LRESULT {
    unsafe {
        let _btn1 = CreateWindowExW(
            0,
            WC_BUTTONW,
            w!("按钮1"),
            WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON as u32,
            150,
            100,
            100,
            30,
            info.window,
            buttons::IDC_BTN1 as HMENU,
            crate::instance(),
            core::ptr::null(),
        );
        println!("wm_create");
    }
    0
}

pub fn wm_command(info: MsgInfo) -> LRESULT {
    unsafe {
        match info.id {
            buttons::IDC_BTN1..=buttons::IDC_BTN5 => {
                buttons::handle_command(info);
            }
            _ => {}
        }
    }
    0
}

pub fn wm_paint(info: MsgInfo) -> LRESULT {
    unsafe {
        let mut ps = PAINTSTRUCT::default();
        let hdc = BeginPaint(info.window, &mut ps);
        // TODO: 这里可以进行绘制操作
        // let sys_brush = GetSysColorBrush(COLOR_WINDOW);
        // FillRect(hdc, &ps.rcPaint, sys_brush);
        use crate::utils;
        let text = format!("window: {:p}", info.window);
        DrawTextW(
            hdc,
            utils::string_to_wide(&text).as_ptr(),
            -1,
            &mut ps.rcPaint as *mut RECT,
            DT_SINGLELINE | DT_CENTER | DT_VCENTER,
        );
        EndPaint(info.window, &ps);
    }
    0
}
